﻿using Marvin.MathematicalFunctions;
using Marvin.Optimization;
using MathNet.Numerics.LinearAlgebra.Double;
using MathNet.Numerics.LinearAlgebra.Generic;

namespace Marvin.Prediction.LinearRegression
{
    public class LinearRegression: PredictionAlgorithm
    {
        private LinearFunction _learnedFunction;
        private Matrix<double> _xMatrix;
        private Vector<double> _y; 


        protected override void Learn()
        {
            var gradient = new GradientFunction(_xMatrix, _y);
            var gradientDescent = new GradientDescent(gradient);
            var parameters = gradientDescent.CalculateMinimum();
            _learnedFunction = new LinearFunction(parameters);

            Reset();
        }

        private void Reset()
        {
            _xMatrix = null;
            _y = null;
        }

        protected override void TransformTrainingSetToInternalRepresentation(TrainingSet<double> trainingSet)
        {
            _xMatrix = trainingSet.GetX();
            _y = new DenseVector( trainingSet.GetY() ) ; 
        }

        public override double Predict(double[] x)
        {
            return _learnedFunction.Calculate(x);
        }
    }
}
